package com.cms.web.servlet;

import com.cms.pojo.Admin;
import com.cms.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    private AdminService service = new AdminService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 获取单选框数据
        int role = Integer.parseInt(request.getParameter("role"));

        // 获取复选框数据
        String remember = request.getParameter("remember");

        // 调用service查询
        Admin admin = service.login(username, password, role);

        // 判断
        if(admin != null) {
            // 登陆成功

            // 判断用户是否勾选记住我
            if("1".equals(remember)) {
                // 勾选了记住我，则发送Cookie

                // 创建Cookie对象
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);

                // 设置Cookie存活时间
                c_username.setMaxAge(60 * 60 * 24 * 7);
                c_password.setMaxAge(60 * 60 * 24 * 7);

                // 发送Cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }

            // 将登陆成功的user对象存到Session中
            HttpSession session = request.getSession();
            session.setAttribute("user", admin);

            // 跳转到已登录首页
            String contextPath = request.getContextPath();
            if (role == 1) {
                response.sendRedirect(contextPath + "/studentIndex.jsp");
            } else if (role == 2) {
                response.sendRedirect("myCourseServlet");
            } else {
                response.sendRedirect("allCourseServlet");
            }
        } else {
            // 登陆失败

            // 将错误信息存到request域
            request.setAttribute("login_msg", "用户名或密码错误");

            // 跳转到login.jsp
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
